require "ruby_odata"
require "xmlsimple"
require "fileutils"

class PackageManager
  @packages_to_install = nil
  @packages_to_delete = nil

  def delete_obsolete_packages
    @packages_to_delete.each do |target|
      path = File.join(File.expand_path("packages"), target + "*")
      Dir.glob(path) do |item|
        FileUtils.remove_dir(item, true)
      end
    end
    puts "All obsolete packages have been removed"
    $stdout.flush
  end

  def load_packages!
    @packages_to_install = Hash.new("")
    @packages_to_delete = Hash.new("")
    service = OData::Service.new "http://packages.nuget.org/v1/FeedService.svc/"
    repositories = XmlSimple.xml_in(File.join("packages", "repositories.config"))
    repositories["repository"].each do |repo|
      path = File.expand_path(repo["path"], "packages")
      XmlSimple.xml_in(path)["package"].each do |pkg|
        begin
          service.Packages.filter("Id eq '" + pkg["id"] + "'").filter("IsLatestVersion eq true")
          package_details = service.execute
          packages = Array.try_convert(package_details)
          if packages
            details = packages[0]
          else
            details = package_details
          end
          unless details == nil
            @packages_to_install[details.Id.to_s] = details.Version.to_s
            unless details.Version == pkg["version"]
              @packages_to_delete[details.Id.to_s] = pkg["version"]
            end
          end
        rescue
        end
      end
    end
    puts "All referenced online packages have been loaded"
    $stdout.flush
  end
  
  def is_package_installed?(package_id)
    desired_package = File.join(File.expand_path("packages"), package_id + "." + @packages_to_install[package_id])
    return File.directory? desired_package
  end
end